package br.edu.ufcg.boombox.view;

import br.edu.ufcg.boombox.controller.ContextoDaAplicacao;
import br.edu.ufcg.boombox.controller.PaginaInicialBoomBoxController;
import br.edu.ufcg.boombox.util.Formatadores;
import java.awt.event.MouseListener;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import br.edu.ufcg.boombox.model.Usuario;
import java.awt.image.BufferedImage;
import java.net.URISyntaxException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Silva
 */
public class PaginaInicialBoomBoxView extends javax.swing.JFrame {

    /**
     * Creates new form PaginaInicialF
     */
    public PaginaInicialBoomBoxView() {
        initComponents();
        inicializarComandos();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        labelTitulo = new javax.swing.JLabel();
        comboBoxTipoPesquisa = new javax.swing.JComboBox();
        fieldPesquisa = new javax.swing.JTextField();
        buttonOkPesquisar = new javax.swing.JButton();
        comboBoxJanelasDePerfil = new javax.swing.JComboBox();
        labelFotoPerfil = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        labelNomeUsuario = new javax.swing.JLabel();
        labelGenero = new javax.swing.JLabel();
        labelContato = new javax.swing.JLabel();
        buttonMinhasListas = new javax.swing.JButton();
        buttonFavoritos = new javax.swing.JButton();
        buttonAmigos = new javax.swing.JButton();
        buttonTodasMusicas = new javax.swing.JButton();
        buttonLocalizarAmigos = new javax.swing.JButton();
        buttonTopList = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Página Inicial");
        setBackground(new java.awt.Color(244, 244, 244));
        setMinimumSize(new java.awt.Dimension(800, 550));

        jPanel1.setBackground(new java.awt.Color(0, 102, 204));
        jPanel1.setPreferredSize(new java.awt.Dimension(714, 45));

        labelTitulo.setFont(new java.awt.Font("Tekton Pro", 1, 22)); // NOI18N
        labelTitulo.setForeground(new java.awt.Color(233, 233, 233));
        labelTitulo.setText("BoomBox");

        comboBoxTipoPesquisa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Busca por", "Música", "Artista", "Álbum", "Gênero" }));

        buttonOkPesquisar.setText("Ok");
        buttonOkPesquisar.setActionCommand("pesquisar");

        comboBoxJanelasDePerfil.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Início", "Configurações", "Sair" }));
        comboBoxJanelasDePerfil.setActionCommand("janelasDePerfil");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(labelTitulo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(comboBoxTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fieldPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonOkPesquisar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(comboBoxJanelasDePerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(50, 50, 50))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelTitulo)
                    .addComponent(comboBoxTipoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fieldPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonOkPesquisar)
                    .addComponent(comboBoxJanelasDePerfil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        labelFotoPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaMasculina.jpg"))); // NOI18N
        labelFotoPerfil.setText("Imagem");
        labelFotoPerfil.setToolTipText("Dê um clique duplo para alterar a imagem do perfil.");

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);

        labelNomeUsuario.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        labelNomeUsuario.setText("Nome do usuário");

        labelGenero.setText("Gênero: Feminino");

        labelContato.setText("Contato:");

        buttonMinhasListas.setText("Minhas Listas");
        buttonMinhasListas.setActionCommand("minhasListas");

        buttonFavoritos.setText("Favoritos");
        buttonFavoritos.setActionCommand("listarFavoritos");

        buttonAmigos.setText("Amigos");
        buttonAmigos.setActionCommand("listarAmigos");

        buttonTodasMusicas.setText("Todas as músicas");
        buttonTodasMusicas.setMaximumSize(new java.awt.Dimension(109, 23));

        buttonLocalizarAmigos.setText("Localizar amigos");
        buttonLocalizarAmigos.setActionCommand("localizarAmigos");

        buttonTopList.setText("Top List");
        buttonTopList.setActionCommand("listaTopList");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 675, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(labelFotoPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jSeparator1)
                    .addComponent(buttonMinhasListas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonFavoritos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonAmigos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelContato)
                    .addComponent(labelGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonLocalizarAmigos, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonTodasMusicas, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonTopList, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(buttonTodasMusicas, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(buttonLocalizarAmigos, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(buttonTopList, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(56, 56, 56)
                                .addComponent(labelGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(42, 42, 42)
                                .addComponent(labelContato))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelFotoPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(buttonMinhasListas, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonFavoritos, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(buttonAmigos, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(0, 21, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PaginaInicialBoomBoxView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAmigos;
    private javax.swing.JButton buttonFavoritos;
    private javax.swing.JButton buttonLocalizarAmigos;
    private javax.swing.JButton buttonMinhasListas;
    private javax.swing.JButton buttonOkPesquisar;
    private javax.swing.JButton buttonTodasMusicas;
    private javax.swing.JButton buttonTopList;
    private javax.swing.JComboBox comboBoxJanelasDePerfil;
    private javax.swing.JComboBox comboBoxTipoPesquisa;
    private javax.swing.JTextField fieldPesquisa;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel labelContato;
    private javax.swing.JLabel labelFotoPerfil;
    private javax.swing.JLabel labelGenero;
    private javax.swing.JLabel labelNomeUsuario;
    private javax.swing.JLabel labelTitulo;
    // End of variables declaration//GEN-END:variables

    private javax.swing.JFileChooser chooser = new JFileChooser();
    
    
    
    public void configuraOuvinte(PaginaInicialBoomBoxController controlador) {
        this.buttonAmigos.addActionListener(controlador);
        this.buttonFavoritos.addActionListener(controlador);
        this.buttonLocalizarAmigos.addActionListener(controlador);
        this.buttonMinhasListas.addActionListener(controlador);
        this.buttonOkPesquisar.addActionListener(controlador);
        this.buttonTodasMusicas.addActionListener(controlador);
        this.buttonTopList.addActionListener(controlador);
        this.comboBoxJanelasDePerfil.addActionListener(controlador);
        this.comboBoxTipoPesquisa.addActionListener(controlador);
        this.fieldPesquisa.addActionListener(controlador);
    }
    
    public void initButtonAmigos() {
        this.buttonAmigos.setActionCommand("listarAmigos");
    }
    
    public void initButtonFavoritos() {
        this.buttonFavoritos.setActionCommand("listarFavoritos");
    }
    
    public void initButtonLocalizarAmigos() {
        this.buttonLocalizarAmigos.setActionCommand("localizarAmigos");
    }
    
    public void initButtonMinhasListas() {
        this.buttonMinhasListas.setActionCommand("minhasListas");
    }
    
    public void initButtonOkPesquisar() {
        this.buttonOkPesquisar.setActionCommand("pesquisar");
    }
    
    public void initButtonTodasMusicas() {
        this.buttonTodasMusicas.setActionCommand("todasMusicas");
    }
    
    public void initButtonTopList() {
        this.buttonTopList.setActionCommand("listaTopList");
    }
    
    public void initComboBoxJanelasDePerfil() {
        this.comboBoxJanelasDePerfil.setActionCommand("janelasDePerfil");
    }
    
    public void initLabelFotoPerfil(MouseListener mouseListener) {
        MouseListener[] mouseListeners = this.labelFotoPerfil.getMouseListeners();
        boolean chave  = false;
        for( int i = 0; i < mouseListeners.length; i++) {
            if(mouseListeners[i] == mouseListener) {
                chave = true;
            }
        }
        if( !chave ){
            this.labelFotoPerfil.addMouseListener(mouseListener);
        }
    }
    
    private void inicializarComandos() {
            initButtonAmigos();
            initButtonFavoritos();
            initButtonLocalizarAmigos();
            initButtonMinhasListas();
            initButtonOkPesquisar();
            initButtonTodasMusicas();
            initButtonTopList();
            initComboBoxJanelasDePerfil();
    }
    
    public String getEstadoAtualDaJanela() {
        return (String) this.comboBoxJanelasDePerfil.getSelectedItem();
    }
    
    //TODO ADICIONAR DEMAIS INIT'S NECESSARIOS
    
    public void atualizar() {
        Usuario usuario = ContextoDaAplicacao.getInstance().getUsuarioLogado();
        this.labelNomeUsuario.setText(Formatadores.formataNomeDeUsuario(usuario.getNome()));
        this.labelGenero.setText(Formatadores.formataGeneroUsuario(usuario.getGenero()));
        byte[] imagemPerfil = usuario.getImagePerfil();
        System.out.println("PATH: "+ getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaFeminina.jpg"));
        if (imagemPerfil == null) {
            if (usuario.getGenero().equals("Feminino")) {
                javax.swing.ImageIcon imageIcon = new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaFeminina.jpg"));
                this.labelFotoPerfil.setIcon(imageIcon);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage imagem = Formatadores.iconToBufferedImage(this.labelFotoPerfil.getIcon());
                byte[] imagemArray = null;
                try {
                    ImageIO.write(imagem, "png", baos);
                    imagemArray = baos.toByteArray();
                } catch (IOException ex) {
                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
                }
                
//                URL url = getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaFeminina.jpg");
//                InputStream itStrm;
//                byte[] imagem = null;
//                try {
//                    itStrm = new FileInputStream(new File(url.toURI()));
//                    imagem = new byte[itStrm.available()];
//                    itStrm.read(imagem);
//                } catch (IOException ex) {
//                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
//                } catch (URISyntaxException ex) {
//                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
//                }
                usuario.setImagePerfil(imagemArray);

            } else if (usuario.getGenero().equals("Masculino")) {
                javax.swing.ImageIcon imageIcon = new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaMasculina.jpg"));
                this.labelFotoPerfil.setIcon(imageIcon);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage imagem = Formatadores.iconToBufferedImage(this.labelFotoPerfil.getIcon());
                byte[] imagemArray = null;
                try {
                    ImageIO.write(imagem, "png", baos);
                    imagemArray = baos.toByteArray();
                } catch (IOException ex) {
                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
                }

//                URL url = getClass().getResource("/br/edu/ufcg/boombox/recurso/silhuetaMasculina.jpg");
//                InputStream itStrm;
//                byte[] imagem = null;
//                try {
//                    itStrm = new FileInputStream(new File(url.toURI()));
//                    imagem = new byte[itStrm.available()];
//                    itStrm.read(imagem);
//                } catch (IOException ex) {
//                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
//                } catch (URISyntaxException ex) {
//                    Logger.getLogger(PaginaInicialBoomBoxView.class.getName()).log(Level.SEVERE, null, ex);
//                }
                usuario.setImagePerfil(imagemArray);
            } else {
                this.labelFotoPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/default.jpg")));
            }
        } else {
            try {
                this.labelFotoPerfil.setIcon(new ImageIcon(imagemPerfil));
            } catch (Exception e) {
                e.printStackTrace();
                this.labelFotoPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/default.jpg")));
            }
        }
    }

    public void clear() {
        this.labelNomeUsuario.setText("");
        this.labelGenero.setText("");
        this.labelContato.setText("");
        this.labelFotoPerfil.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/ufcg/boombox/recurso/default.jpg")));
        this.comboBoxJanelasDePerfil.setSelectedIndex(0);
    }
    
}
